package cn.itsource.hrm.web.controller;

import cn.itsource.hrm.exception.GloabException;
import cn.itsource.hrm.utils.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice   //a的外丝 对 RestController 增强，指定的方法前后添加代码
public class GloabExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public AjaxResult ExceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("后台故障，我们正在殴打程序员...");
    }


    @ExceptionHandler(GloabException.class)
    public AjaxResult GloabExceptionHandler(GloabException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        //((FieldError)((java.util.LinkedList)((BeanPropertyBindingResult)e.bindingResult).errors).get(0)).defaultMessage
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer sb = new StringBuffer();
        allErrors.forEach(objectError -> {
            sb.append(objectError.getDefaultMessage()+"; ");
        });
        return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+sb.toString());
    }
}
